package com.lanxi.nbpaytest.Service.Impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.IoUtil;
import com.lanxi.nbpaytest.Service.PayService;
import com.nbcb.pluto.pay.sdk.PayUtil;
import com.nbcb.pluto.pay.sdk.utils.BaseHttpSSLSocketFactory;
import org.springframework.stereotype.Service;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLSession;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.ProtocolException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * @Author mintaoyu
 * Date on 2020-02-25  15:28
 */

@Service
public class PayServiceImpl implements PayService {

    private static final String APP_ID = "3000160000";


    @Override
    public void init() {
        String rootPath = "/home/";
//        String rootPath = this.getClass().getResource("/").getFile();
        // 测试证书
        String pfxPath = rootPath +"old"+ APP_ID + "/" + APP_ID + ".pfx";
        String certPath = rootPath +"old"+ APP_ID + "/" + APP_ID + ".cer";
        // 生产证书
//        String pfxPath = rootPath + APP_ID + "/" + APP_ID + ".pfx";
//        String certPath = rootPath + APP_ID + "/" + "paygate.cer";
        String pfxPwd = "123456";
        PayUtil.init(pfxPath, pfxPwd, certPath);
    }

    @Override
    public void formalInit() {
        String rootPath = "/home/";
        // 生产证书
        String pfxPath = rootPath + APP_ID + "/" + APP_ID + ".pfx";
        String certPath = rootPath + APP_ID + "/" + APP_ID + ".cer";
        String pfxPwd = "123456";
        PayUtil.init(pfxPath, pfxPwd, certPath);
    }

    @Override
    public String sign(String body) {
        System.out.println("签名原文：" + body);
        String signMsg = null;
        try {
            signMsg = PayUtil.sign(body);
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("签名值：" + signMsg);
        return signMsg;
    }

    @Override
    public boolean validate(String body, String signMsg) {
        try {
//            String rootPath = "/home/";
//            String certPath = rootPath  + "paygate.cer";
            String certPath = "/home/" + "old" + APP_ID + "/" + APP_ID + ".cer";

            return PayUtil.validate(certPath, body, signMsg);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    @Override
    public String createAutoFormSubmitHtml(String appId, String reqUrl, String body, String signMsg) {
        return PayUtil.createAutoFormSubmitHtml(appId, reqUrl, body, signMsg);
    }

    @Override
    public String post(String appId, String url, String body) {
        try {
            return PayUtil.post(appId, url, body);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public List<ArrayList<String>> myPost(String appId, String url, String body) {
        HttpURLConnection httpConn = null;
        OutputStream out = null;
        BufferedReader in = null;
        String var11;
        try {
            URL urlClient = new URL(url);
            httpConn = (HttpURLConnection) urlClient.openConnection();
            setHttpConnection(appId, httpConn);
            out = httpConn.getOutputStream();
            out.write(body.getBytes("UTF-8"));
            out.flush();
            InputStream is = httpConn.getInputStream();
            in = IoUtil.getReader(is, "UTF-8");
            String contentLine;
            List<ArrayList<String>> rows = new ArrayList<>();
            while ((contentLine = in.readLine()) != null) {
                String[] split = contentLine.split(",", -1);
                ArrayList<String> strings = CollUtil.newArrayList(split);
                rows.add(strings);
            }
            return rows;
        } catch (Exception var23) {
            try {
                throw var23;
            } catch (IOException e) {
                e.printStackTrace();
            }
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (IOException var22) {
                    var22.printStackTrace();
                }
            }

            if (in != null) {
                try {
                    in.close();
                } catch (IOException var21) {
                }
            }

        }

        return null;
    }

    @Override
    public InputStream backInputStream(String appId, String url, String body) {
        HttpURLConnection httpConn = null;
        OutputStream out = null;
        try {
            URL urlClient = new URL(url);
            httpConn = (HttpURLConnection) urlClient.openConnection();
            setHttpConnection(appId, httpConn);
            out = httpConn.getOutputStream();
            out.write(body.getBytes("UTF-8"));
            out.flush();
            return httpConn.getInputStream();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private static void setHttpConnection(String appId, HttpURLConnection httpConn) throws ProtocolException {
        httpConn.setRequestMethod("POST");
        httpConn.setConnectTimeout(5000);
        httpConn.setReadTimeout(60000);
        setGwHeader(appId, httpConn);
        httpConn.setRequestProperty("Connection", "keep-alive");
        httpConn.setRequestProperty("Accept-Language", "zh-CN,zh;q=0.8");
        httpConn.setRequestProperty("Content-Type", "application/json;charset=utf-8");
        httpConn.setRequestProperty("Accept", "application/json;charset=utf-8");
        httpConn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/14.0.803.0 Safari/535.1");
        httpConn.setDoInput(true);
        httpConn.setDoOutput(true);
        if ("https".equalsIgnoreCase(httpConn.getURL().getProtocol())) {
            HttpsURLConnection husn = (HttpsURLConnection) httpConn;
            husn.setSSLSocketFactory(new BaseHttpSSLSocketFactory());
            husn.setHostnameVerifier(new HostnameVerifier() {
                @Override
                public boolean verify(String arg0, SSLSession arg1) {
                    return true;
                }
            });
        }

    }

    private static void setGwHeader(String appId, HttpURLConnection httpConn) {
        httpConn.setRequestProperty("X-GW-APP-ID", appId);
        httpConn.setRequestProperty("X-GW-SDK-VERSION", "1.0.1");
        httpConn.setRequestProperty("X-GW-NONCE", UUID.randomUUID().toString());
        httpConn.setRequestProperty("X-GW-TIME", System.currentTimeMillis() + "");
        httpConn.setRequestProperty("X-GW-TIME-OFFSET", "0");
    }
}
